﻿function PostsVm() {
    var self = this;
    this.posts = ko.observableArray();
    this.page = ko.observable();
    this.url = ko.observable();
    this.getMoreEnabled = ko.observable(true);
    this.isAuthor = ko.observable(false);
    this.authorName = ko.observable();
    this.authorUrl = ko.observable();
    this.total = ko.observable();
    this.count = ko.observable(0);
    this.pageCount = ko.observable();

    this.find = function (id) {
        for (idx = 0; idx < this.posts().length; idx++) {
            if (this.posts()[idx].fileId() == id)
                return this.posts()[idx];
        }
    }

    this.loadJson = function (data) {
        for (idx = 0; idx < data.length; idx++) {
            var postVm = new PostVm(this);
            postVm.loadJson(data[idx]);
            this.posts.push(postVm);
        }
        if (this.page() >= this.pageCount())
            this.getMoreEnabled(false);
    }

    this.setAuthor = function (name, url) {
        this.isAuthor(true);
        this.authorName(name);
        this.authorUrl(url);
    }

    this.getMore = function () {
        var url = this.url()
        url += (url.indexOf('?') == -1) ? '?page=' : '&page=';
        url += this.page();

        $.get(url, function (data) {
            if (data.Result) {
                self.page(self.page() + 1);
                self.loadJson(data.Data);

            } else {
                self.getMoreEnabled(false);
            }
        });
    }
}